package com.huifaapp.mall.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huifaapp.mall.R;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.Goods;
import com.huifaapp.mall.bean.RegisterBean;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by duanyu on 2018/1/20.
 */

public class Red_PacketActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView moneyTV;
    private TextView nameTV;
    private TextView timeSlotTV;
    private ImageView goodsImgIV;
    private TextView goodsDescribeTV;
    private TextView goodsSaleNumTV;
    private TextView goodsOriginalCostTV;
    private TextView prizeTicketAfterPrizeTV;
    private Button prize_ticket_btn;
    private Button paktetact_btn;
    private String id;
    private String shopid;
    private String typex;
    private LinearLayout back_btn;
    private String Isspceial="立即抢购";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_red_paktetactivity);
        final Intent intent=getIntent();
        shopid = intent.getStringExtra("shopid");
        Log.e("Goodid", shopid);
        typex = intent.getStringExtra("typex");
        Log.e("typex", typex);
        Log.e("appid",AUniqueIdentifier.getDeviceId(Red_PacketActivity.this));
        Log.e("tyen", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
        initView();
        Log.e("领红包页", ApiManager.BASE_NIUPAI_URL+"coupon/info"+"?appId="+
                AUniqueIdentifier.getDeviceId(Red_PacketActivity.this)+"&token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&type=1"+"&goodsId="+shopid);
        String goodsUrl = ApiManager.BASE_NIUPAI_URL+"coupon/info";
        OkHttpUtils
                .post()
                .url(goodsUrl)
                .addParams("appId", AUniqueIdentifier.getDeviceId(Red_PacketActivity.this))
                .addParams("token",SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("type","1")
                .addParams("goodsId",shopid)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response) throws IOException {
                        try {
                            String jsonContent = response.body().string();
                            Log.e("udfgiuh", jsonContent);
                            Gson gson = new Gson();
                            final Goods goods = gson.fromJson(jsonContent, Goods.class);
                            if (goods.getCode().equals("10000")) {
                                final Goods.DataBean.GoodInfoBean goodInfo = goods.getData().getGoodInfo();
                                final Goods.DataBean data = goods.getData();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        String money = String.valueOf((int) data.getPrice());
                                        moneyTV.setText(money + "");
                                        timeSlotTV.setText(data.getStartTime() + "\t-\t" + data.getEndTime());
                                        Glide.with(Red_PacketActivity.this).load(goodInfo.getMainImg()).into(goodsImgIV);
                                        goodsDescribeTV.setText(goodInfo.getGoodName());
                                        goodsSaleNumTV.setText("已抢" + goodInfo.getTotalSales() + "件/评价");
                                        goodsOriginalCostTV.setText("原价 ￥" + goodInfo.getPrice());
                                        prizeTicketAfterPrizeTV.setText(goodInfo.getConPrice() + "");
                                        id = data.getId();
                                        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
                                        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        try {
                                            Date date = sdf.parse(data.getEndTime());

                                        if(curDate.after(date)){
                                            prize_ticket_btn.setBackgroundResource(R.drawable.text_red_bg_a_hui_yuan);
                                            prize_ticket_btn.setText("已过期");
                                            prize_ticket_btn.setClickable(false);
                                        }else{
                                            if (data.getState() == 1) {
                                            prize_ticket_btn.setBackgroundResource(R.drawable.text_red_bg_a_hui_yuan);
                                            prize_ticket_btn.setText("已领取");
                                            prize_ticket_btn.setClickable(false);
                                        } else {
                                            if (data.getState() == 3) {
                                                Toast.makeText(Red_PacketActivity.this, "请登录领取", Toast.LENGTH_LONG).show();
                                                prize_ticket_btn.setClickable(false);
                                            }
                                            prize_ticket_btn.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    http2();
                                                }
                                            });
                                        }
                                        }
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });

                            }else{

                            }
                            }catch(Exception e){
                                Log.e("red", e.getMessage());
                            }
                        return null;
                    }

                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(Object response) {

                    }
                });


    }

    private void http2() {
        Map<String,String>Stringmap=new HashMap<>();
        Stringmap.put("appId", AUniqueIdentifier.getDeviceId(Red_PacketActivity.this));
        Stringmap.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
        Stringmap.put("type","1");
        Stringmap.put("couponId",id);
        OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"coupon/receive").params(Stringmap).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Log.e("红包领取",response);
                Gson gson=new Gson();
                RegisterBean redReceiveBean = gson.fromJson(response, RegisterBean.class);
                if(redReceiveBean.getCode().equals("10000")){
                    Intent intent1=new Intent(Red_PacketActivity.this,ShoppingCartActivity.class);
                    intent1.putExtra("shopid",shopid);
                    intent1.putExtra("typex",typex);
                    intent1.putExtra("Isspceial",Isspceial);
                    startActivity(intent1);
                    prize_ticket_btn.setBackgroundResource(R.drawable.text_red_bg_a_hui_yuan);
                    prize_ticket_btn.setText("已领取");
                    prize_ticket_btn.setClickable(false);
                }else if(redReceiveBean.getCode().equals("10001")){
                    Intent intent = new Intent(Red_PacketActivity.this, LoginActivity.class);
                    startActivity(intent);
                }else if(redReceiveBean.getCode().equals("10002")){
                    Intent intent = new Intent(Red_PacketActivity.this, LoginActivity.class);
                    startActivity(intent);
                }else
                if (redReceiveBean.getCode().equals("10071")){
                    prize_ticket_btn.setBackgroundResource(R.drawable.text_red_bg_a_hui_yuan);
                    prize_ticket_btn.setText("已领取");
                    prize_ticket_btn.setClickable(false);

                    Intent intent1=new Intent(Red_PacketActivity.this,ShoppingCartActivity.class);
                    intent1.putExtra("shopid",shopid);
                    intent1.putExtra("typex",typex);
                    intent1.putExtra("Isspceial",Isspceial);
                    startActivity(intent1);

                }else if(redReceiveBean.getCode().equals("10072")){
                    Toast.makeText(Red_PacketActivity.this,redReceiveBean.getMsg(),Toast.LENGTH_SHORT).show();
                    prize_ticket_btn.setBackgroundResource(R.drawable.text_red_bg_a_hui_yuan);
                    prize_ticket_btn.setText("已过期");
                    prize_ticket_btn.setClickable(false);
//                    Intent intent1=new Intent(Red_PacketActivity.this,ShoppingCartActivity.class);
//                    intent1.putExtra("shopid",shopid);
//                    intent1.putExtra("typex",typex);
//                    intent1.putExtra("Isspceial",Isspceial);
//                    startActivity(intent1);
                }else {
                    Toast.makeText(Red_PacketActivity.this,redReceiveBean.getMsg(),Toast.LENGTH_SHORT).show();
                }

            }



        });
    }

    private void initView() {
        Isspceial = getIntent().getStringExtra("Isspceial");
        moneyTV = (TextView) findViewById(R.id.hongbao_value_tv);
        nameTV = (TextView) findViewById(R.id.hongbao_applying_conditions_tv);
        timeSlotTV = (TextView) findViewById(R.id.prize_ticket_date_tv);
        goodsImgIV = (ImageView) findViewById(R.id.goods_img_iv);
        goodsDescribeTV = (TextView)findViewById(R.id.goods_describe_tv);
        goodsSaleNumTV = (TextView)findViewById(R.id.goods_sale_num_tv);
        goodsOriginalCostTV = (TextView)findViewById(R.id.goods_original_cost_tv);
        prizeTicketAfterPrizeTV = (TextView)findViewById(R.id.prize_ticket_after_prize_tv);
        prize_ticket_btn = (Button) findViewById(R.id.prize_ticket_btn);
        paktetact_btn = (Button) findViewById(R.id.paktetact_btn);
        back_btn = (LinearLayout) findViewById(R.id.back_btn);
        paktetact_btn.setOnClickListener(this);
        back_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.paktetact_btn:

                Log.e("去详情页","----------------------------------");
                Intent intent1=new Intent(Red_PacketActivity.this,ShoppingCartActivity.class);
                intent1.putExtra("shopid",shopid);
                intent1.putExtra("typex",typex);
                intent1.putExtra("Isspceial", Isspceial);
                startActivity(intent1);
                break;
            case R.id.back_btn:
                finish();
                break;
        }

    }
}